package com.hw.nio.channel;



import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.FileChannel;

/**
 * @author 车宏伟
 * @date 2021/1/13 9:41
 */
public class FileChannelTest {

    String filePath = "F:\\work\\nettyStydyMaven\\test.txt";

    @Test
    public void test() throws IOException {
        FileInputStream fileInputStream = new FileInputStream(filePath);
//        FileChannel channel = fileInputStream.getChannel();  // 读管道
        // 读写管道 rw
        java.nio.channels.FileChannel channel = new RandomAccessFile(filePath, "rw").getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 循环读取数据
        while ((channel.read(buffer)) != -1) {
            channel.read(buffer);
            buffer.flip();
            byte[] bytes = new byte[buffer.remaining()];
            int i = 0;
            while (buffer.hasRemaining()) {
                bytes[i++] = buffer.get();
            }
            buffer.clear();
            System.out.println(new String(bytes));
        }
        // 写入数据到文件
        long position = channel.position();
        System.out.println("position: " + position);
        buffer.mark();
        buffer.put("哈哈啊哈".getBytes());
        buffer.reset();
//        channel.write(ByteBuffer.wrap("哈哈哈".getBytes()));
//        buffer.rewind();
        channel.write(buffer);
    }
}
